#include "Game.h"
#include "PatrolAI.h"
#include "Graphics/Mainloader.h"
#include "Graphics/Anim.h"
#include "Graphics/Anim_Pack.h"
#include "Graphics/Graphic_Module.h"

Game::Game(MainGraphic & nmg, IMap & map)
    : _mg(nmg), _map(map), _bulletPool(10), _patrolPool(2), _mobPool(2), _player(NULL), _objs(), _ais()
{
    GameObject::mg = &nmg;
    _player = new Mobile(vector(32, 32), vector(), vector(22, 44));
    _player->setGraphicComponent("player");}

void Game::init()
{
    _objs.push_front(_player);

    Mobile * monster = new Mobile(vector(2550, 1000), vector(), vector(32, 32));
    monster->setGraphicComponent("monster");
    _objs.push_front(monster);
    PatrolAI * ai = _patrolPool.getNext();
    ai->setMobile(monster);
    _ais.push_front(ai);

    monster = new Mobile(vector(1050, 200), vector(), vector(32, 18));
    monster->setGraphicComponent("monster");
    _objs.push_front(monster);
    ai = _patrolPool.getNext();
    ai->setMobile(monster);
    _ais.push_front(ai);
}

void Game::update(float elapsedTime, action & action)
{
    Bullet * bullet;

    // INPUT
    if (action.left)
        _player->move(GameObject::LEFT);
    else if (action.right)
        _player->move(GameObject::RIGHT);
    if (action.jump)
        _player->jump();
    if (action.shoot == action::SHOOT_MAX)
    {
        bullet = _bulletPool.getNext();
        bullet->init(_player);
        _objs.push_front(bullet);
    }

    // AI
    for (std::list<AAI*>::iterator AIit = _ais.begin(); AIit != _ais.end(); ++AIit)
        (*AIit)->update();

    std::list<GameObject*>::iterator it, nit;

    for (it = _objs.begin(); it != _objs.end(); ++it)
    {
        nit = it;
        for (++nit; nit != _objs.end(); ++nit)
            (*it)->checkCollision(*(*nit), elapsedTime);
        (*it)->update(elapsedTime, _map);
        if (!(*it)->isActive())
        {
            if (*it != _player && (_mobPool.disposeOf(static_cast<Mobile*>(*it)) || _bulletPool.disposeOf(static_cast<Bullet*>(*it))));
            it = _objs.erase(it);
        }
    }
}
